import pymysql
import time
import base64
import hashlib
from datetime import datetime, timedelta
import re
import sys
import getopt
import random


con = pymysql.connect('114.215.192.224','jr1','JRyhdweb123','quzizhu',charset='utf8')


cur = con.cursor()


def insert(sql, args=None):
    cur.execute(sql,args)
    con.commit()
    return cur.lastrowid


def select(sql):
    cur.execute(sql)
    return cur.fetchall()


def get_hash_str():
    """
    用来生成短连接
    """
    md5 = hashlib.md5()
    md5.update(str(time.time()).encode('utf-8'))
    digest = md5.digest()
    hash_str = str(base64.b64encode(digest),'utf-8')
    ret = []
    for i in hash_str:
        if  (i >= '0' and i <='9') or (i>='a' and i<='z') or (i>='A' and i<='Z'):
            ret.append(i)
            if len(ret) == 6:
                break
    print(ret)
    return ''.join(ret)


def build_detail_text(text_list):
    s = ''
    a,b =  text_list[1].strip().split(' ',1)

    s += a + '<br>' + b + '<br>'

    for item in text_list[2:]:
        item = item.strip()
        if item != '':
            s += item + '<br>' 
    return s


def publish_qiugou():
    with open('ewood_detail.txt') as f:
        l = f.readline()
        n = 0

        while n < 100:
            n += 1
            item = l.strip().split(',')

            list = item[0].split('&&&')
            title = list[0]
            if len(list) > 1:
                detail_text = list[1]
            else:
                detail_text = list[0]
            address = get_random_city()
            # detail_text = build_detail_text(list)
            # title = item[0].lstrip('求购：')
            # address = item[9].lstrip('采购地址：')
            type = '托盘料'
            # print(detail_text)
            # if re.search('[\d]{11}',title):
            #     l = f.readline()
            #     continue
            # print(title)
            # print(address)
            hash_str = get_hash_str()
            print(hash_str)
            id = insert("insert into stpc_qzz_demand (title,type,origin,hash_str,detail_text,size,price) values ('{}','{}','{}','{}','{}','{}','{}')".format(
                title,type,address,hash_str,detail_text,'定制电议',0
            ))
            insert("insert into stpc_qzz_short_link (c_name, hash_str, p_name, p_id) values('{}','{}','{}',{})".format(
                'DdAction',hash_str, 'page', id
            ))
            l = f.readline()
            time.sleep(180)


def publish_zixun():
    """
    """
    data = select("select * from stpc_qzz_article_bak limit 6600,150")
    for i in data:
        hash_str = get_hash_str()
        title = i[1]
        content = i[4]
        source = '网络转载'
        print(title)
        if title[:4] == '2020' or title[2] == '年':
            year = datetime.now().year
            month = datetime.now().month
            day = datetime.now().day
            num = title.find('日')
            if num == -1:
                num = title.find('月')
            else:
                num = title.find('日')
            num = num + 1
            titlea = title[num:]
            title = str(year) + '年' + str(month) + '月' + str(day) + '日' + titlea
            print(title)
            # print(titlea)
        summary = i[4].strip()[:50] + '...'  if i[4].strip()[0] != '<' else title
        print(hash_str)
        try:
            insert_id = insert("""
            insert into stpc_qzz_news (title, introduce, content, source, hash_str, addtime, updatetime)
             values ("{}","{}", '{}','{}' ,'{}' ,'{}','{}')
            """.format(title,summary,content,source,hash_str, datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S'),
            datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S')))
        except:
            continue
        insert("""
        insert into stpc_qzz_short_link (c_name, hash_str, p_name, p_id) values('{}','{}','{}',{})
        """.format(
                'NdAction',hash_str, 'page', insert_id
            ))
        time.sleep(180)


def publish_goods():
    """
    发布商品
    """
    data = select("select * from stpc_qzz_provider_bak limit 200,100")
    
    print(data)
    for item in data:
        imgs = select('select * from stpc_qzz_provider_img_bak where goods_id={}'.format(item[14]))
        if not imgs:
            print('no image')
            continue
        insert_id = insert("""
        insert into stpc_qzz_provider (name, type,size,origin,trad_place,price,hash,detail_text,thumb,unit)  values (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s) 
        """,  (get_random_city() + item[1],)   + item[2:6] + (item[8],) + item[10:14])
        print(item[14])
        print(imgs)
        print(insert_id)
        for img in imgs:
            print(img)
            img_id = insert("""
            insert into stpc_qzz_provider_img (provid_id, img, type) values (%s,%s,%s)
            """, (insert_id,) + img[2:4])
            print(img_id)
        insert(
            """
            insert into stpc_qzz_short_link (c_name, hash_str, p_name, p_id) values('{}','{}','{}',{})
            """.format('SpdAction',item[10],'page',insert_id)
        )
        time.sleep(10)


def get_random_city():
    """
    
    """
    return random.choice([
"北京",
"七台河",
"三亚",
"三明",
"三沙",
"上饶",
"东莞",
"东营",
"中卫",
"中山",
"临汾",
"临沂",
"临沧",
"丹东",
"丽水",
"丽江",
"乌海",
"乐山",
"九江",
"云浮",
"亳州",
"伊春",
"佛山",
"保定",
"保山",
"信阳",
"六安",
"兰州",
"兴安盟",
"内江",
"包头",
"北海",
"十堰",
"南京",
"南宁",
"南平",
"南昌",
"南通",
"南阳",
"厦门",
"台州",
"台湾省",
"合肥",
"吉安",
"吉林",
"吕梁",
"周口",
"咸宁",
"唐山",
"商丘",
"商洛",
"嘉兴",
"四平",
"固原",
"大同",
"大庆",
"大连",
"天水",
"威海",
"娄底",
"孝感",
"宁德",
"宁波",
"安庆",
"安康",
"安阳",
"安顺",
"宜宾",
"宜昌",
"宜春",
"宝鸡",
"宣城",
"宿州",
"宿迁",
"岳阳",
"崇左",
"巴中",
"常州",
"常德",
"平凉",
"广元",
"广州",
"庆阳",
"廊坊",
"开封",
"张掖",
"徐州",
"德州",
"忻州",
"怀化",
"惠州",
"成都",
"扬州",
"承德",
"抚州",
"抚顺",
"拉萨",
"新乡",
"新余",
"无锡",
"日照",
"昆明",
"昭通",
"晋中",
"晋城",
"普洱",
"曲靖",
"朝阳",
"本溪",
"来宾",
"杭州",
"松原",
"枣庄",
"柳州",
"株洲",
"桂林",
"梅州",
"梧州",
"榆林",
"武威",
"武汉",
"永州",
"汉中",
"汕头",
"汕尾",
"江门",
"池州",
"沈阳",
"沧州",
"河池",
"河源",
"泉州",
"泰安",
"泰州",
"泸州",
"洛阳",
"济南",
"济宁",
"海口",
"淄博",
"淮北",
"淮南",
"淮安",
"深圳",
"清远",
"温州",
"渭南",
"湖州",
"湘潭",
"湛江",
"滁州",
"滨州",
"漯河",
"漳州",
"潍坊",
"潮州",
"濮阳",
"烟台",
"焦作",
"玉林",
"玉溪",
"珠海",
"白城",
"白山",
"白银",
"百色",
"益阳",
"盐城",
"盘锦",
"眉山",
"福州",
"绍兴",
"绥化",
"绵阳",
"聊城",
"肇庆",
"自贡",
"舟山",
"苏州",
"茂名",
"荆州",
"荆门",
"莆田",
"莱芜",
"菏泽",
"萍乡",
"营口",
"蚌埠",
"衡水",
"衡阳",
"衢州",
"襄阳",
"西宁",
"西安",
"许昌",
"贵港",
"贺州",
"资阳",
"赣州",
"赤峰",
"辽源",
"辽阳",
"达州",
"运城",
"通化",
"通辽",
"遂宁",
"遵义",
"邢台",
"邯郸",
"邵阳",
"郑州",
"郴州",
"鄂州",
"酒泉",
"金华",
"金昌",
"钦州",
"铁岭",
"铜川",
"铜陵",
"银川",
"锦州",
"镇江",
"长春",
"长沙",
"长治",
"阜新",
"阜阳",
"阳江",
"阳泉",
"陇南",
"随州",
"雅安",
"青岛",
"鞍山",
"韶关",
"鸡西",
"鹤壁",
"鹤岗",
"鹰潭",
"黄冈",
"黄山",
"黄石",
"黑河",
"龙岩",
"七台河",
"三门峡",
"佳木斯",
"六盘水",
"双鸭山",
"和田地区",
"哈尔滨",
"喀什地区",
"嘉峪关",
"塔城地区",
"平顶山",
"张家口",
"张家界",
"攀枝花",
"景德镇",
"牡丹江",
"石嘴山",
"石家庄",
"秦皇岛",
"葫芦岛",
"连云港",
"阿拉善盟",
"阿里地区",
"马鞍山",
"驻马店",
"乌兰察布",
"乌鲁木齐",
"克拉玛依",
"呼伦贝尔",
"呼和浩特",
"巴彦淖尔",
"鄂尔多斯",
"锡林郭勒盟",
"阿克苏地区",
"阿勒泰地区",
"齐齐哈尔",
"大兴安岭地区",
"临夏回族自治州",
"凉山彝族自治州",
"大理白族自治州",
"昌吉回族自治州",
"果洛藏族自治州",
"楚雄彝族自治州",
"海南藏族自治州",
"澳门特别行政区",
"玉树藏族自治州",
"甘南藏族自治州",
"甘孜藏族自治州",
"迪庆藏族自治州",
"黄南藏族自治州",
"伊犁哈萨克自治州",
"延边朝鲜族自治州",
"怒江傈僳族自治州",
"巴音郭楞蒙古自治州",
"文山壮族苗族自治州",
"西双版纳傣族自治州",
"阿坝藏族羌族自治州",
"德宏傣族景颇族自治州",
"恩施土家族苗族自治州",
"海西蒙古族藏族自治州",
"湘西土家族苗族自治州",
"红河哈尼族彝族自治州",
"黔东南苗族侗族自治州",
"黔南布依族苗族自治州",
"克孜勒苏柯尔克孜自治州",
"黔西南布依族苗族自治州",
    ])

     
if __name__ == "__main__":
    argv = sys.argv[1:]
    try:
        opts , args = getopt.getopt(argv,'t:')
    except:
        print('eg : python3 publish.py -t qiugou')
    
    for opt, arg in opts:
        if opt == '-t':
            locals()['publish_' + arg]()
        else:
            print('eg: python3 publish.py -t qiugou')
